package com.ficus.road.maintain.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.StringReader;

/**
 * @className: SoapUtil
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/12/25
 **/
public class SoapUtil {

    // 从 SOAP XML 中提取 JSON 字符串
    public static String extractJsonFromSoap(String soapXml) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(soapXml)));

        // 获取 <return> 元素中的 JSON 字符串
        Node returnNode = document.getElementsByTagName("return").item(0);
        return returnNode.getTextContent().trim();
    }

    // 修改 JSON 内容，更新指定 signsCode 对应的 signsValue
    public static String modifyJson(String jsonContent, String targetSignsCode, double newSignsValue) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();

        // 解析 JSON 数组
        JsonNode root = objectMapper.readTree(jsonContent);
        for (JsonNode node : root) {
            // 查找 signsCode 为指定值的对象
            if (node.get("signsCode").asText().equals(targetSignsCode)) {
                ((ObjectNode) node).put("signsValue", newSignsValue); // 修改 signsValue
            }
        }

        // 返回修改后的 JSON 字符串
        return objectMapper.writeValueAsString(root);
    }

    // 将修改后的 JSON 内容插入回原 SOAP XML
    public static String replaceJsonInSoap(String soapXml, String modifiedJson) throws Exception {
        // 使用 DOM 解析 SOAP XML，并替换 JSON 部分
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(soapXml)));

        Node returnNode = document.getElementsByTagName("return").item(0);
        returnNode.setTextContent(modifiedJson);

        // 将修改后的 Document 转换回字符串
        return documentToString(document);
    }

    // 将 Document 转换为字符串
    public static String documentToString(Document document) throws Exception {
        DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
        LSSerializer lsSerializer = domImplLS.createLSSerializer();
        return lsSerializer.writeToString(document);
    }
}
